﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using Vit.Caching;
using Vit.Common.Extensions;

namespace Vit.Data
{
    public class CachingConnectionVisitor : DbConnectionVisitorBase
    {
        private ICacheManager cm;

        public CachingConnectionVisitor(ICacheManager cm)
        {
            this.cm = cm;
        }

        public override void OnCommandExecuting(object sender, CommandExecutionEventArgs e)
        {
            string key = GetKey(e.Command, e.Method);
            if (this.cm.Contains(key))
            {
                e.Result = cm.GetData(key);
                e.Cancel = true;
            }
        }

        public override void OnCommandExecuted(object sender, CommandExecutionEventArgs e)
        {
            string key = GetKey(e.Command, e.Method);
            if(e.Command.AffectedEntities.Count > 0)
                this.cm.Add(key, e.Result, e.Command.AffectedEntities, TimeSpan.FromDays(1.0), DateTime.Now.AddDays(1.0));
        }

        public override void OnCommandFailed(object sender, CommandExecutionEventArgs e)
        {
        }

        public override void OnTransactionCommit(object sender, TransactionEventArgs e)
        {
            if (e.AffectedEntities.Count > 0)
                this.cm.RemoveDependancySet(e.AffectedEntities);
        }

        public override void OnTransactionRollback(object sender, TransactionEventArgs e)
        {
        }

        private string GetKey(DbCommandWrapper cmd, string method)
        {
            return string.Format("CONN:{0},CMD:{1},MD:{2}", cmd.Connection.ConnectionString, cmd.ToUniqueName(), method);
        }
    }
}
